package com.loong.system.controller.common;

import com.loong.common.mongo.file.MongoFileService;
import com.loong.common.mvc.BaseForeheadController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @Description:
 * @Author: hzp
 * @Date: 2020-11-27 17:45
 */
@Slf4j
@RestController
@RequestMapping("forehead/system/file")
public class ForeheadFileController extends BaseForeheadController {


    @Autowired
    private MongoFileService mongoFileService;

    @GetMapping(path = "/get/{id}")
    public void loadFile(@PathVariable String id, HttpServletResponse response) {
        GridFsResource gridFsResource = mongoFileService.get(id);
        if (ObjectUtils.isEmpty(gridFsResource)) {
            return;
        }
        dealOut(response, gridFsResource);
    }

    private void dealOut(HttpServletResponse response, GridFsResource gridFsResource) {
        try(OutputStream outputStream = response.getOutputStream()) {
            response.setContentType(gridFsResource.getContentType());
            outputStream.write(IOUtils.toByteArray(gridFsResource.getInputStream()));
            outputStream.flush();
        } catch (Exception ex) {
            log.error("/forehead/system/file/get error", ex);
        }
    }
}
